import { onMounted, ref } from "vue";
import { getQiniuToken, postAction } from "../command/netTool";
import * as vant from "vant";
const { showFailToast, showLoadingToast, closeToast } = vant;

export const useList = () => {};

// 自定义文件上传
export const useUploader = (params: any) => {
  let qiniu = ref({ token: "", url: "", region: "" });
  onMounted(() => {
    getQiniuToken().then((e) => (qiniu.value = e));
  });
  function upload(callBack: (url: string) => void) {
    const dom = document.getElementById("uploadFile") as HTMLInputElement;
    dom.type = "file";
    dom.hidden = true;
    dom.onchange = function (data: any) {
      const file = data.target.files[0];
      if (params.type == "word") {
        if (
          !["doc", "docx", "pdf", "word", "excel"].some((e) =>
            file.name.includes(e)
          )
        ) {
          showFailToast("类型不符合要求");
          return;
        }
      }

      if (file) {
        const form = new FormData();
        form.append("file", file);
        form.append("token", qiniu.value.token);
        showLoadingToast({
          message: "上传中...",
          forbidClick: true,
        });
        try {
          postAction(qiniu.value.region || "https://up-z2.qiniup.com", form)
            .then((e) => {
              closeToast();
              dom.value = "";
              callBack(qiniu.value.url + e.key);
            })
            .catch(() => {
              showFailToast("上传失败");
            });
        } catch (error) {
          showFailToast("上传失败");
        }
      }
    };
    dom.click();
  }
  return {
    upload,
  };
};
